<template>
  <a-drawer
      title="账单列表"
      :maskClosable="true"
      :visible="visible"
      :width="$store.getters.isMobile ? 350 : 1100"
      @close="closeModal"
      :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
      paddingBottom: '80px',
    }"
  >
    <a-alert type="info" v-if="!processApprove" style="margin-bottom: 10px;">
      <template #message>
        匹配流水暂未开启审批，点击”
        <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
        <span v-else class="link" style="cursor: not-allowed;">配置</span>
        “可快速设置。
      </template>
    </a-alert>
    <a-row type="flex" align="middle">
      <a-col :flex="1">
        <a-input-search
            v-model:value="keywords"
            placeholder="搜索房号"
            enter-button
            @search="onKeywordsSearch"
            allow-clear
        />
      </a-col>
      <a-col>
        <div style="display: flex">
          <div class="switch-wrap">
            <a-switch
                v-model:checked="isExpandOwner"
                checked-children="显示"
                un-checked-children="隐藏"
                @change="onOwnerSwitchChange"
            />
            <span
                style="font-size: 12px; padding: 0 8px">{{
                `已${isExpandOwner ? '显示' : '隐藏'}其他${$L("租客账单")}`
              }}</span>
          </div>
          <div class="switch-wrap">
            <a-switch
                v-model:checked="incomeBillsBeforeDate"
                checked-children="显示"
                un-checked-children="隐藏"
                @change="onIncomeSwitchChange"
            />
            <span style="font-size: 12px; padding: 0 8px">{{
                incomeBillsBeforeDate
                    ? "已显示未到应收期账单"
                    : "已隐藏未到应收期账单"
              }}</span>
          </div>
        </div>
      </a-col>
    </a-row>

    <a-table
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        :row-selection="rowSelection"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        class="mt-10"
        :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'price'">
          <span>{{ text }}元</span>
        </template>
        <template v-if="column.key === 'period'">
          <span>{{ record.start_date }} ~ {{ record.end_date }}</span>
        </template>
        <template v-if="column.key === 'contract_number'">
          <span>{{ text || "--" }}</span>
        </template>
      </template>
    </a-table>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="closeModal">取消</a-button>
        <a-button
            type="primary"
            @click.prevent="matchToTurnover"
            :disabled="selectedRowKeys.length == 0"
        >匹配
        </a-button
        >
      </a-space>
    </div>
    <!-- 匹配弹窗 -->
    <a-modal
        v-model:visible="showMatchModal"
        title="账单匹配"
        centered
        :width="600"
    >
      <a-form layout="vertical">
        <a-row :gutter="12">
          <a-col :span="12">
            <a-form-item
                label="匹配金额（元）"
                v-bind="validateInfos.match_price"
            >
              <a-input-number
                  class="w-100p"
                  placeholder="请输入匹配金额"
                  v-model:value="matchParams.match_price"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="匹配时间" v-bind="validateInfos.match_date">
              <a-date-picker
                  class="w-100p"
                  v-model:value="matchParams.match_date"
                  :value-format="dateFormatStr"
                  :disabled-date="disabledDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-descriptions layout="vertical" bordered>
              <a-descriptions-item label="账单未匹配">
                {{ matchParams.billUnmatch }}元
              </a-descriptions-item>
              <a-descriptions-item label="流水未匹配">
                {{ matchParams.turnoverUnmatch }}元
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
        <a-row v-if="processApprove" :gutter="24" style="margin-top: 10px;">
          <a-col :span="24">
            <a-form-item label="审批备注">
              <a-textarea
                  v-model:value="matchParams.approval_remark"
                  :auto-size="{ minRows: 3, maxRows: 6 }"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" :loading="btnLoading" @click="onSubmit">
            {{ processApprove ? '确定&发起审批' : '确定' }}
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </a-drawer>

  <SelectCostType
      :visible="selectCostVisible"
      :value="costList"
      @closeModal="selectCostVisible = false"
      @costConfirm="costConfirm"
  />
</template>

<script>
import {defineComponent, watch, reactive, toRefs, computed, ref} from "vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import moment from "moment";
import {Form, message} from "ant-design-vue";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
import _ from "lodash";
import BLCOMMON from "bl-common-vue3";
import SelectCostType from "@/components/SelectCostType/index.vue";
import {SearchOutlined} from "@ant-design/icons-vue";
import utils from "@/common/utils/utils";

export default defineComponent({
  name: "TurnoverBillList",
  components: {SearchOutlined, SelectCostType},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    content: {
      type: Object,
      default: () => ({}),
    },
    cost_type: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const today = moment();
    const disabledDate = (current) => {
      return current && current < moment().subtract(1, "days").endOf("day");
    };

    watch(
        () => store.getters.incomeBillsBeforeDate,
        (val) => {
          state.incomeBillsBeforeDate = val;
        }
    );

    // 隐藏&&显示未到应收期账单
    const onIncomeSwitchChange = (checked) => {
      store.dispatch("SetIncomeBillsBeforeDate", checked).then(() => {
        state.page = 1;
        getTableData();
      });
    };

    const onOwnerSwitchChange = (checked) => {
      store.dispatch("SetMatchBillsShowOtherOwner", checked).then(() => {
        state.page = 1;
        getTableData();
      });
    };

    watch(
        () => store.getters.matchBillsShowOtherOwner,
        (val) => {
          state.isExpandOwner = val;
        }
    );
    const matchToTurnover = () => {
      const {content} = props;
      matchParams.turnoverUnmatch = Number(content.nomatch_price);
      matchParams.billUnmatch = 0;
      for (let item of state.selectedRows) {
        matchParams.billUnmatch =
            Number(matchParams.billUnmatch) +
            Number(item.receivable_payment) -
            Number(item.matchPrice);
      }
      matchParams.billUnmatch = Number(matchParams.billUnmatch).toFixed(2);
      matchParams.match_price =
          Number(matchParams.turnoverUnmatch) > Number(matchParams.billUnmatch)
              ? matchParams.billUnmatch
              : matchParams.turnoverUnmatch;
      state.showMatchModal = true;
    };
    const closeModal = () => {
      context.emit("cancel");
    };

    const onSubmit = () => {
      let msgContent = "";
      if (matchParams.match_price < 0) {
        msgContent = "匹配金额不能小于0";
      }
      if (
          matchParams.turnoverUnmatch > matchParams.billUnmatch &&
          matchParams.match_price > matchParams.billUnmatch
      ) {
        msgContent = `匹配金额不能大于账单未匹配总金额`;
      }
      if (
          matchParams.billUnmatch > matchParams.turnoverUnmatch &&
          matchParams.match_price > matchParams.turnoverUnmatch
      ) {
        msgContent = "匹配金额不能大于流水未匹配总金额";
      }
      if (msgContent) {
        message.error(msgContent);
        return;
      }

      state.btnLoading = true;
      let params = {
        stream_id: props.content.id,
        approval: state.processApprove,
        ...matchParams,
        bill_ids: state.selectedRowKeys.join(","),
        needMsg: true,
      };
      params.match_date = moment(params.match_date).format(dateFormatStr);
      request
          .post("/org", "/stream/matchBill", {
            ...params,
          })
          .then((res) => {
            state.btnLoading = false;
            message.success(res.msg || "匹配成功！");
            state.showMatchModal = false;
            context.emit("success");
          });
    };

    const state = reactive({
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      optionData: {},
      showMatchModal: false,
      btnLoading: false,
      projectList: [], // 项目
      buildList: [], // 楼宇
      selectCostVisible: false,

      incomeBillsBeforeDate: false,
      isExpandOwner: false,
      // 是否有审批
      processApprove: true,
      Approveis_admin: false,
      Approve_id: 0,
    });

    const searchParams = reactive({
      keywords: "",
      order: "",
      sort: "",
      costList: [],
      build_ids: [], // 多个用英文逗号相连
      village_ids: [], // 多个用英文逗号相连
      loan_type: props.content.loan_type,
    });

    const matchParams = reactive({
      match_price: "",
      approval_remark: "",
      match_date: today,
      billUnmatch: 0,
      turnoverUnmatch: 0,
    });
    const matchRule = ref({
      match_price: [{required: true, message: "必填"}],
      match_date: [{required: true, message: "必填"}],
    });
    const {resetFields, validate, validateInfos} = useForm(
        matchParams,
        matchRule
    );

    const onKeywordsSearch = () => {
      if (state.page == 1) {
        getTableData();
      } else {
        state.page = 1;
      }
    };

    watch(
        () => searchParams.keywords,
        (val) => {
          if (!val) {
            onKeywordsSearch();
          }
        }
    );

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectChange,
    }));

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      state.selectedRowKeys = selectedRowKeys;
      if (selectedRowKeys.length == selectedRows.length) {
        state.selectedRows = selectedRows;
      } else {
        selectedRows = [...selectedRows, ...state.selectedRows];
        state.selectedRows = [];
        selectedRows.forEach((item) => {
          if (selectedRowKeys.includes(item.id)) {
            const index = state.selectedRows.findIndex(
                (it) => it.id == item.id
            );
            if (index == -1) {
              state.selectedRows.push(item);
            }
          }
        });
      }
      // console.log(" state.selectedRowKeys ", state.selectedRowKeys);
      // console.log(" state.selectedRows ", state.selectedRows);
    };

    const columns = computed(() => {
      const {streamInit} = props.content;
      return [
        {
          title: BLCOMMON.utils.L("项目名称"),
          dataIndex: "villageName",
          fixed: store.getters.isMobile ? undefined : "left",
          filters:
              state.projectList && state.projectList.length
                  ? state.projectList.map((item) => ({
                    value: item.id,
                    text: item.name,
                  }))
                  : [],
          width: 130,
        },
        {
          title: BLCOMMON.utils.L("楼宇名称"),
          key: "buildName",
          dataIndex: "buildName",
          width: store.getters.isMobile ? 100 : 160,
          fixed: "left",
          filters:
              state.buildList && state.buildList.length
                  ? state.buildList.map((item) => ({
                    value: item.id,
                    text: item.build_name,
                  }))
                  : [],
          filteredValue: searchParams.build_ids || [],
        },
        {
          title: "付款方",
          key: "owner_name",
          dataIndex: "owner_name",
          width: 160,
          fixed: store.getters.isMobile ? undefined : "left",
        },

        {
          title: "楼层-房号",
          key: "roomInfo",
          dataIndex: "roomInfo",
          width: 200,
        },
        {
          title: "费用类型",
          key: "cost_type_txt",
          dataIndex: "cost_type_txt",
          width: 140,
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              state.selectCostVisible = visible;
            }
          },
          filtered: !!searchParams.costList?.length,
        },
        {
          title: "应收金额",
          key: "price",
          dataIndex: "receivable_payment",
          sorter: true,
          width: 120,
        },
        {
          title: "已匹配金额",
          key: "price",
          dataIndex: "matchPrice",
          width: 120,
        },
        {
          title: "应收时间",
          key: "receivable_payment_date",
          dataIndex: "receivable_payment_date",
          sorter: true,
          width: 120,
        },
        {
          title: "计费周期",
          key: "period",
          dataIndex: "start_date",
          width: 200,
        },
        // {
        //   title: "关联合同",
        //   key: "contract_number",
        //   dataIndex: "contract_number",
        //   width: 160,
        // },
      ];
    });

    // 根据选择的项目 动态展示筛选楼宇的list
    const getBuildList = () => {
      let villages = [];
      let searchVillageIds = searchParams.village_ids;
      if (searchVillageIds?.length) {
        state.projectList.forEach((v) => {
          if (searchVillageIds.find((a) => a === v.id)) {
            villages.push(v);
          }
        });
      } else {
        villages = _.cloneDeep(state.projectList);
      }
      getBuildListByVillage(villages);
    };

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      // console.log("filters", filters);
      // console.log("sorter", sorter);
      // 排序
      if (sorter.order) {
        searchParams.order = sorter.field;
        searchParams.sort = sorter.order === "ascend" ? "asc" : "desc";
      } else {
        searchParams.order = "";
        searchParams.sort = "";
      }
      // 项目
      searchParams.village_ids = filters?.villageName?.length
          ? filters.villageName
          : [];

      getBuildList();
      // 多选
      let filterBuild = filters?.buildName?.length ? filters.buildName : [];
      if (filterBuild.length) {
        let build = [];
        // 处理 去除掉不要的
        filterBuild.forEach((a) => {
          if (state.buildList.find((v) => v.id === a)) {
            build.push(a);
          }
        });
        // 楼宇
        searchParams.build_ids = build;
      } else {
        searchParams.build_ids = [];
      }
      getTableData();
    };

    const costConfirm = (list) => {
      state.selectCostVisible = false;
      searchParams.costList = _.cloneDeep(list);
      getTableData();
    };

    const getTableData = () => {
      state.loading = true;
      const params = {
        cost_type: props.cost_type,
        owner_id: props.content.company_id,
        owner_name: props.content.company_name,
        page: state.page,
        limit: state.limit,
        loan_type: props.content.loan_type,
        stream_id: props.content.id,
      };
      for (let key in searchParams) {
        if (searchParams[key]) {
          if ("costList" === key) {
            if (searchParams.costList?.length) {
              params.cost_type = searchParams.costList
                  .map((v) => {
                    return v.value;
                  })
                  .join(",");
            } else {
              params.cost_type = "";
            }
          } else if (["build_ids"].includes(key)) {
            if (searchParams[key]?.length) {
              params[key] = searchParams[key].join(",");
            } else {
              params[key] = "";
            }
          } else {
            params[key] = searchParams[key];
          }
        }
      }
      params.is_show = state.incomeBillsBeforeDate;
      if (state.isExpandOwner) {
        delete params.owner_id;
        delete params.owner_name;
      }
      request
          .post("/org", "/stream/matchBillList", params)
          .then((res) => {
            state.total = res.total;
            state.dataList = res.data;
          })
          .finally(() => {
            state.loading = false;
          });
    };

    const getBuildListByVillage = (list) => {
      let checkedBuild = [];
      list.forEach((village) => {
        if (village?.buildList?.length) {
          village.buildList.forEach((build) => {
            checkedBuild.push(build);
          });
        }
      });
      state.buildList = checkedBuild;
    };

    const screenList = () => {
      request
          .get("/org", "/build/villageAndBuildList", {checked: 1})
          .then((res) => {
            state.projectList = res.villageList;
            getBuildListByVillage(state.projectList);
          });
    };

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'bill_stream_match'
      }).then((res) => {
        state.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id
      });
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    const handleCancel = () => {
      state.showMatchModal = false
    };

    const init = () => {
      state.incomeBillsBeforeDate = store.getters.incomeBillsBeforeDate;
      state.isExpandOwner = store.getters.matchBillsShowOtherOwner;
      screenList();
      store.dispatch("SetBMTInit").then((res) => {
        state.optionData = res;
      });
      getTableData();
    };

    const reset = () => {
      resetFields();
      state.page = 1;
      state.selectedRowKeys = [];
      state.selectedRows = [];
      state.projectList = [];
      state.buildList = [];
    };

    watch(
        () => props.visible,
        (visible) => {
          if (visible) {
            init();
          } else {
            reset();
          }
          getSetting();
        }
    );
    return {
      ...toRefs(state),
      ...toRefs(searchParams),
      matchParams,
      validateInfos,
      pagination,
      columns,
      rowSelection,
      dateFormatStr,
      closeModal,
      matchToTurnover,
      onKeywordsSearch,
      handleTableChange,
      onSubmit,
      disabledDate,
      costConfirm,
      onIncomeSwitchChange,
      onOwnerSwitchChange,
      getSetting,
      goSetting,
      handleCancel,
    };
  },
});
</script>
<style lang="less" scoped>
.switch-wrap {
  margin-left: 16px;
  background-color: #f2f2f2;
  border-radius: 20px;
  padding: 5px 10px;
  display: flex;
  align-items: center;
}
</style>
